#include "Day.h"
Day::Day(day_t day) : currentDay(day){

}

Day::~Day(){
}

Day::Day(const Day &day){
	//Appointments are contained in each day
	this->currentDay = day.currentDay;
	this->appointments.insert(day.appointments.begin(),day.appointments.end());	
}


day_t Day::getDay() const{
	return currentDay;
}
	
bool Day::makeAppointment(hour startHour, hour endHour, std::string &subject){
	try{
		Appointment app(startHour,endHour,subject);
		map<hour,Appointment,timeComparator>::iterator it = appointments.find(startHour);
		if(it == appointments.end()){
			//a potential make
			for(it = appointments.begin(); it != appointments.end(); ++it){
				/*if(app.getStartTime() < it->second.getStartTime() && app.getEndTime() < it->second.getStartTime()){
					break;
				}
				if(!(app.getStartTime() <= it->second.getStartTime() || app.getStartTime() <= it->second.getEndTime())){
					break;
				}*/
				if(it->second == app){
					//overlap hour
					return false;
				}
			}
			//insert app			
			appointments.insert(pair<time,Appointment>(startHour,app));
		}else{
			//there exists an appointment with the same start hour
			return false;
		}
	}catch(int err){
		//constructor failed
		return false;
	}
	return true;
}

bool Day::moveAppointment(hour startHour, hour newStartHour){
	// see if that app. exists
	map<hour,Appointment,timeComparator>::iterator it = appointments.find(startHour);
	if(it != appointments.end()){
		// try to add new appointment
		bool bMake = makeAppointment(newStartHour,it->second.getEndTime()+it->second.getDuration(),it->second.getSubject());
		if(bMake){
			// remove from old position
			removeAppointment(startHour);
		}
	}	
	return false;
}

const Day& Day::operator =(const Day &day){
	if(this != &day){	
		this->currentDay = day.currentDay;
		this->appointments.clear();
		this->appointments.insert(day.appointments.begin(),day.appointments.end());		
	}
	return *this;
}

void Day::removeAppointment(hour startHour){
	//remove from map
	appointments.erase(startHour);
}

Appointment* Day::findAppointment(hour startHour)const{
	//find in map and return a pointer
	map<hour,Appointment,timeComparator>::const_iterator it = appointments.find(startHour);
	if(it != appointments.end()){
		return (Appointment*)&it->second;
	}
	return 0;
}

Appointment* Day::getFirstAppointment()  const{
	//Gets the first appointement in the day
	map<hour,Appointment,timeComparator>::const_iterator it = appointments.begin();
	if(it != appointments.end()){
		return (Appointment *)&it->second;
	}
	return 0;
}